package com.tongren.framework.fragment;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;
import com.tongren.framework.R;
import com.tongren.framework.api.Api;
import com.tongren.framework.callback.JsonCallback;
import com.tongren.framework.constants.ConstantValues;
import com.tongren.framework.core.BaseFragment;
import com.tongren.framework.core.BaseListFragment;
import com.tongren.framework.core.ITabFragment;
import com.tongren.framework.model.BaseModel;
import com.tongren.framework.model.Benefit;
//import com.tongren.framework.model.CoreMenu;
//import com.tongren.framework.model.HttpResult;
import com.tongren.framework.widgets.pull.BaseViewHolder;
import com.tongren.framework.widgets.pull.PullRecycler;

import java.util.ArrayList;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * zhangxu
 */
public class NewsList3Fragment extends BaseListFragment<Benefit> implements ITabFragment {
    private int page = 1;
    private boolean isInitCache = false;

    public static NewsList3Fragment newInstance(int page) {
        NewsList3Fragment fragment = new NewsList3Fragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ConstantValues.KEY_FRAGMENT_PAGE, page);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        enableLazyLoad();
    }

    @Override
    protected BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.news_list_item, parent, false);
        return new SampleViewHolder(view);
    }

//    @Override
//    protected ILayoutManager getLayoutManager() {
//        MyLinearLayoutManager layoutManager = new MyLinearLayoutManager(getContext());
//        return layoutManager;
////        return new MyGridLayoutManager(getContext(), 3);
//    }

    @Override
    protected RecyclerView.ItemDecoration getItemDecoration() {
        return null;
    }

    @Override
    public void setUpData() {
        if (mDataList == null) {
            recycler.setRefreshing();
        }
    }

    /**
     *
     * @param outState
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(ConstantValues.KEY_SAVE_LIST, mDataList);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mDataList = (ArrayList<Benefit>) savedInstanceState.getSerializable(ConstantValues.KEY_SAVE_LIST);
    }

    //    @Override
//    protected ILayoutManager getLayoutManager() {
//        return new MyStaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
//    }

    @Override
    public void onRefresh(final int action) {
        if (mDataList == null) {
            mDataList = new ArrayList<>();
        }

        if (action == PullRecycler.ACTION_PULL_TO_REFRESH) {
            page = 1;
        }
        OkGo.<BaseModel<ArrayList<Benefit>>>get("http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/"+page++)//请求方式和请求url
                .tag(this)//请求的 tag, 主要用于取消对应的请求
//                .headers("header1", "headerValue1")//
//                .params("page", page++)//
//                .params("limit", 10)//
                .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)  //缓存模式先使用缓存,然后使用网络数据
                .execute(new JsonCallback<BaseModel<ArrayList<Benefit>>>() {
                    @Override
                    public void onSuccess(Response<BaseModel<ArrayList<Benefit>>> response) {
//                        handleResponse(response);
                        String str = response.toString();
                        System.out.println(str);
                        if (action == PullRecycler.ACTION_PULL_TO_REFRESH) {
                            mDataList.clear();
                        }
                        if (response.body().results == null ||response.body().results.size() == 0) {
                            recycler.enableLoadMore(false);
                        } else {
                            recycler.enableLoadMore(true);
                            mDataList.addAll(response.body().results);
                            adapter.notifyDataSetChanged();
                        }
                        recycler.onRefreshCompleted();
                    }

                    @Override
                    public void onCacheSuccess(Response<BaseModel<ArrayList<Benefit>>> response) {
                        //一般来说,只需呀第一次初始化界面的时候需要使用缓存刷新界面,以后不需要,所以用一个变量标识
                        if (!isInitCache) {
                            //一般来说,缓存回调成功和网络回调成功做的事情是一样的,所以这里直接回调onSuccess
                            onSuccess(response);
                            isInitCache = true;
                        }
                    }

                    @Override
                    public void onError(Response<BaseModel<ArrayList<Benefit>>> response) {
//                        handleError(response);
                        recycler.onRefreshCompleted();
                    }
                });
    }

    @Override
    public void onMenuItemClick() {

    }

    @Override
    public BaseFragment getFragment() {
        return this;
    }

    class SampleViewHolder extends BaseViewHolder {

        ImageView iv_new_img;
        TextView tv_new_title;
        TextView tv_new_date;

        public SampleViewHolder(View itemView) {
            super(itemView);
            tv_new_title = (TextView) itemView.findViewById(R.id.tv_new_title);
            tv_new_date = (TextView) itemView.findViewById(R.id.tv_new_date);
            iv_new_img = (ImageView) itemView.findViewById(R.id.iv_new_img);
        }

        @Override
        public void onBindViewHolder(int position) {
            Glide.with(iv_new_img.getContext())
                    .load(mDataList.get(position).url)
                    .centerCrop()
                    .placeholder(R.color.app_primary_color)
                    .crossFade()
                    .into(iv_new_img);
        }

        @Override
        public void onItemClick(View view, int position) {

        }

    }
}
